package info.thereisonlywe.core.objects;

import java.util.ArrayList;
import java.util.HashSet;

public class WordPool {

	private final ArrayList<HashSet<String>> pool;
	private final ArrayList<Character> indices;

	public WordPool()
	{
		pool = new ArrayList<HashSet<String>>();
		indices = new ArrayList<Character>();
	}

	public synchronized void add(String word)
	{
		Character c = Character.valueOf(word.charAt(0));
		int index = indices.indexOf(c);
		if (index == -1)
		{
			indices.add(c);
			pool.add(new HashSet<String>());
			pool.get(indices.size() - 1).add(word);
		}
		else
		{
			pool.get(index).add(word);
		}
	}

	public void add(String[] words)
	{
		for (int i = 0; i < words.length; i++)
		{
			add(words[i]);
		}
	}

	public synchronized void remove(String word)
	{
		Character c = Character.valueOf(word.charAt(0));
		int index = indices.indexOf(c);
		pool.get(index).remove(word);
		if (pool.get(index).isEmpty())
		{
			pool.remove(index);
		}
	}

	public synchronized boolean contains(String word)
	{
		return pool.get(indices.indexOf(Character.valueOf(word.charAt(0))))
				.contains(word);
	}

	public boolean containsWordsLike(String word)
	{
		Character c = Character.valueOf(word.charAt(0));
		int index = indices.indexOf(c);
		if (index == -1)
		{
			return false;
		}
		else
		{
			for (String str : pool.get(index))
			{
				if (str.startsWith(word)) { return true; }
			}
			return false;
		}
	}

	public ArrayList<String> getWordsLike(String word)
	{
		Character c = Character.valueOf(word.charAt(0));
		int index = indices.indexOf(c);
		if (index == -1)
		{
			return null;
		}
		else
		{
			ArrayList<String> result = new ArrayList<String>();
			for (String str : pool.get(index))
			{
				if (str.startsWith(word))
				{
					result.add(str);
				}
			}
			return result;
		}
	}
}
